package com.rabbit.demo.ylr.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName Consumer
 * @Description TODO
 * @Author 11
 * @Date 2021/7/14 11:07
 * @Version 1.0
 */
public class Consumer {
    public static void main(String[] args) {
//        1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
//        2.设置连接属性
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection = null;
        Channel channel = null;


        try {
//        3. 从连接属性中获取连接
            connection = factory.newConnection();
//        4. 从连接中获取通道channel
            channel = connection.createChannel();

            channel.basicConsume("queue1", true, new DeliverCallback() {
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
                    System.out.println("accept message is :" + new String(message.getBody(), "UTF-8"));
                }
            }, new CancelCallback() {
                @Override
                public void handle(String consumerTag) throws IOException {
                    System.out.println("accept message failed!");
                }
            });

            System.out.println("start accept ！");

            System.in.read();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            if (channel !=null && channel.isOpen())
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
        }



    }
}
